package com.syys.qa.controller;

import com.alibaba.fastjson.JSONObject;
import com.syys.common.annotation.Log;
import com.syys.common.core.controller.BaseController;
import com.syys.common.enums.BusinessType;
import com.syys.common.utils.MessageUtils;
import com.syys.qa.domain.QaRecord;
import com.syys.qa.domain.QaTheme;
import com.syys.qa.service.IQaRecordService;
import com.syys.qa.service.IQaThemeService;
import com.syys.qa.util.UrlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 问卷主题Controller
 *
 * @author ys
 * @date 2021-07-01
 */
@Controller
@RequestMapping("/qa")
public class QaController extends BaseController {
    private String prefix = "qa";
    private static final Logger LOGGER = LoggerFactory.getLogger(QaController.class);

    @Autowired
    private IQaThemeService qaThemeService;
    @Autowired
    private IQaRecordService qaRecordService;

    @GetMapping()
    @Log(title = "问卷访问", businessType = BusinessType.OTHER)
    public String qa(String q, ModelMap mmap, HttpServletRequest request) {
        QaRecord qaRecord = new QaRecord();
        mmap.put("qaRecord", qaRecord);
        try {
            String s = UrlUtil.deCryptAndDecode(q);
            JSONObject jsonObject = JSONObject.parseObject(s);
            qaRecord.setThemeId(Long.parseLong(jsonObject.get("themeId") + ""));
        } catch (Exception e) {
            LOGGER.error("问卷访问异常!", e);
            mmap.put("errorMessage", MessageUtils.message("qa.path") + e.getMessage());
            return prefix + "/bad";
        }
        QaTheme qaTheme = qaThemeService.selectQaThemeById(qaRecord.getThemeId());
        if (qaTheme == null) {
            mmap.put("errorMessage", MessageUtils.message("qa.path"));
            return prefix + "/bad";
        }
//        String ipAddress = IpUtil.getIpAddress(request);
//        qaRecord.setIp(ipAddress);
//        List<QaRecord> qaRecords = qaRecordService.selectQaRecordList(qaRecord);
//        if (qaRecords != null && qaRecords.size() > 0) {
//            mmap.put("errorMessage", MessageUtils.message("qa.repeat"));
//            return prefix + "/bad";
//        }
        return prefix + "/qa";
    }

    @GetMapping("thanks")
    public String thanks(String q, ModelMap mmap, HttpServletRequest request) {
        mmap.addAttribute("q", q);
        return prefix + "/thanks";
    }

}
